<template>
    <div class="sign-up-box">
        <home-header ref="homeHeader" :nav="nav" :logo="logoInfo"></home-header>
        <main class="content-box">
            <div class="content">
                <div class="title">
                    {{ isRestPassword ? '重置密码' : '注册' }}
                </div>
                <!-- 注册 -->
                <el-form :model="form" :rules="rules" ref="form" label-position="label-position" v-if="!isRestPassword">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" auto-complete="off" clearable placeholder="用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email" auto-complete="off" clearable placeholder="邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="tel">
                        <el-input v-model="form.tel" auto-complete="off" clearable placeholder="手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="form.password" show-password auto-complete="off"
                            placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="resPassword">
                        <el-input type="password" v-model="form.resPassword" show-password auto-complete="off"
                            placeholder="请输入确认密码"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码" prop="code">
                        <el-input v-model="form.code" auto-complete="off" placeholder="请输入验证码">
                            <template slot="append">
                                <el-button type="text" @click="getMsgCode" :disabled="timeScend != 60">{{ timeScend != 60 ?
                                    timeScend + 's后重试' : '获取邮箱验证码' }}</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item class="btn-submit-box">
                        <el-button type="primary" @click="submitForm('form')">注册</el-button>
                    </el-form-item>
                    <el-form-item class="btn-submit-box btn-submit-box-phone">
                        <el-button round type="primary" @click="submitForm('form')">注册</el-button>
                    </el-form-item>
                </el-form>

                <!-- 重置密码 -->
                <el-form :model="restForm" :rules="restRules" ref="restForm" label-position="label-position" v-else>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="restForm.email" auto-complete="off" clearable placeholder="邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码" prop="code">
                        <el-input v-model="restForm.code" auto-complete="off" placeholder="请输入验证码">
                            <template slot="append">
                                <el-button type="text" @click="getMsgCode" :disabled="timeScend != 60">{{ timeScend != 60 ?
                                    timeScend + 's后重试' : '获取邮箱验证码' }}</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="restForm.password" show-password auto-complete="off"
                            placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="resPassword">
                        <el-input type="password" v-model="restForm.resPassword" show-password auto-complete="off"
                            placeholder="请输入确认密码"></el-input>
                    </el-form-item>
                    <el-form-item class="btn-submit-box">
                        <el-button type="primary" @click="restPassword('restForm')">重置密码</el-button>
                    </el-form-item>
                    <el-form-item class="btn-submit-box btn-submit-box-phone">
                        <el-button round type="primary" @click="restPassword('restForm')">重置密码</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </main>
        <public-footer :userInfo="logoInfo" :links="links" :isTransparent="true"></public-footer>
    </div>
</template>
<script>
import HomeHeader from '~/components/home-header/index.vue';
import publicFooter from "~/components/public-footer/index.vue";
import request from '~/request/request';
import { showToast } from '~/utils/index';
export default {
    name: 'signup',
    async asyncData({ app , query }) {
        try {
            let nav = await request('/api/index/getNav');
            let logoInfo = await request('/api/index/getBlogTitle');
            let links = await request('/api/index/getLink');
            if(query.type == 'reset') {
                app.head.title = '重置密码'
            } else {
                app.head.title = '注册'
            }
            return {
                nav: nav.data,
                logoInfo: logoInfo.data,
                links: links.data,
                isRestPassword: query.type == 'reset'
            }
        } catch (error) {
            return {}
        }
    },
    components: {
        HomeHeader,
        publicFooter
    },
    data() {
        return {
            form: {
                username: '',
                email: '',
                tel: '',
                password: '',
                resPassword: '', // 确认密码
                code: '',
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的邮箱', trigger: 'blur' }
                ],
                tel: [
                    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '密码长度为6-20', trigger: 'blur' }
                ],
                resPassword: [
                    { required: true, message: '请输入确认密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '密码长度为6-20', trigger: 'blur' },
                    { validator: this.validateResPassword, trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 6, max: 6, message: '验证码长度为6', trigger: 'blur' }
                ]
            },
            links: [],
            nav: [],
            logoInfo: {},
            timeScend: 60, // 验证码倒计时
            timer: null,
            isRestPassword : false  , // 是否重置密码
            restForm : {
                email: '',
                code: '',
                password: '',
                resPassword: ''
            },
            restRules : {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的邮箱', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 6, max: 6, message: '验证码长度为6', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '密码长度为6-20', trigger: 'blur' }
                ],
                resPassword: [
                    { required: true, message: '请输入确认密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '密码长度为6-20', trigger: 'blur' },
                    { validator: this.validateResPassword, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        /**确认密码校验*/
        validateResPassword(rule, value, callback) {
            let password = this.isRestPassword ? this.restForm.password : this.form.password;
            if (value !== password) {
                callback(new Error('两次输入密码不一致'));
            } else {
                callback();
            }
        },
        /**获取邮箱验证码*/
        getMsgCode() {
            let email = this.isRestPassword ? this.restForm.email : this.form.email;
            if (!email) return showToast({ msg: '请输入邮箱', type: 'error' });
            if (this.timer) return;
            request(`/api/email/getCodeByEmail?email=${email}`).then(res => {
                if (res.code === 200) {
                    this.timer = setInterval(() => {
                        if (this.timeScend <= 0) {
                            clearInterval(this.timer);
                            this.timer = null;
                            this.timeScend = 60;
                        } else {
                            this.timeScend--;
                        }
                    }, 1000)
                    showToast({
                        msg: '验证码已发送',
                        type: 'success'
                    });
                } else {
                    showToast({
                        msg: res.message || '验证码发送失败',
                        type: 'error'
                    });
                }
            }).catch(err => {
                showToast({
                    msg: err.message || '验证码发送失败',
                    type: 'error'
                });
            })
        },
        /**注册*/
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    request({
                        url: '/api/users/register',
                        method: 'post',
                        data: this.form
                    }).then(res => {
                        if (res.code === 200) {
                            showToast({
                                msg: '注册成功',
                                type: 'success'
                            });
                            this.$router.push('/');
                        } else {
                            showToast({
                                msg: res.message || '注册失败',
                                type: 'error'
                            });
                        }
                    }).catch(err => {
                        showToast({
                            msg: err.message || '注册失败',
                            type: 'error'
                        });
                    })
                } else {
                    return false;
                }
            });
        },
        /**重置密码*/
        restPassword(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    request({
                        url: '/api/users/webResetPassword',
                        method: 'post',
                        data: this.restForm
                    }).then(res => {
                        if (res.code === 200) {
                            showToast({
                                msg: '重置密码成功',
                                type: 'success'
                            });
                            this.$router.push('/');
                        } else {
                            showToast({
                                msg: res.message || '重置密码失败',
                                type: 'error'
                            });
                        }
                    }).catch(err => {
                        showToast({
                            msg: err.message || '重置密码失败',
                            type: 'error'
                        });
                    })
                } else {
                    return false;
                }
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.sign-up-box {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: repeat-x #bee1f5;
    z-index: -1;

    .content-box {
        height: calc(100% - 125px);
        position: relative;

        .content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 16px;
            box-shadow: 0 4px 8px 6px rgba(7, 17, 21, 0.06);
            border-radius: 8px;
            background-color: #fff;
            width: 600px;

            .title {
                font-size: 24px;
                font-weight: 600;
                text-align: center;
                margin-bottom: 20px;
            }

            .btn-submit-box {
                display: block;
            }

            .btn-submit-box-phone {
                display: none;
            }
        }
    }

    /deep/.el-button--primary {
        background-color: var(--themeColor);
        border-color: var(--themeColor);
    }

    /deep/.el-form-item {
        margin-bottom: 0px;

        .el-form-item__label {
            line-height: normal;
            padding-bottom: 5px;
        }

        .el-form-item__error {
            top: 3px;
            left: auto;
            right: 10px;
        }

        .el-form-item__content {
            line-height: normal;
        }

    }

    .btn-submit-box {
        text-align: center;
        margin-top: 10px;

        .el-button {
            width: 100%;
        }
    }
}

@media screen and (max-width: 768px) {
    .sign-up-box {
        position: relative;
        background: #fff;
        z-index: inherit;

        .content-box {
            height: 100%;

            .content {
                width: 100%;
                padding: 16px 20px;
                box-shadow: none;
                position: relative;
                transform: none;
                left: 0;
                top: 0;

                .btn-submit-box {
                    display: none;
                }

                .btn-submit-box-phone {
                    display: block;
                }
            }
        }
    }
}</style>